(function(D){
    D.initFiles = function(line) 
    {
	var files = document.getElementById("files"),
	    lines = document.getElementById("lines");

	var updateFiles = function(){
		D.request("getFiles.txt",
			{
				"collectionId": line.id
			}, function(results){
				var filesLabels = document.getElementById("filesLabels"),
				    numberOfFiles = filesLabels.childNodes.length;

				for(var i=0; i<numberOfFiles; i+=1){
					filesLabels.removeChild(filesLabels.childNodes[0]);	
				}

				for(var i=0; i<results.length; i+=1){
					var fileLabel = document.createElement("a");

					fileLabel.setAttribute("class", "fileLabel");
					fileLabel.setAttribute("href", "");
					fileLabel.innerHTML = decodeURIComponent(results[i].fileLabel.value);
					filesLabels.appendChild(fileLabel);

					fileLabel.onmouseup = function(){
						var collectionId = results[i].file.value;

						return function(){
							if(D.dragObject.type === "page"){
							    var dragObject = D.dragObject;
							    var pageId = dragObject.line.images[ dragObject.i ].id;
							    
							    D.request("getCollectionImages.txt",
							    	{
									"collectionId": collectionId
								},
								function(results){
							    		D.request( "addPageToCollection.txt",
							    		    {
							    			"collectionId": collectionId,
							    			"page": pageId,
							    			"numPage": results.length + 1,
							    			"timestamp": new Date( ).getTime( ),
							    			"user": D.userName( )
							    		    },null, true );
								}
							    );
							}
						}
					}();

					fileLabel.onclick = function(){
						var collectionId = results[i].file.value;

						return function(){
							D.newLine(collectionId);
							return false;
						}
					}();
				}
			}
		);
	}

	var addToHeight = function(elem,delta){
		elem.style.height = (parseInt(elem.style.height) + delta) + "px";
	}

	$("#newFileBtn").mouseup(function(){
		var collectionLabel = $("#newFileName").val(),
		    timestamp = new Date( ).getTime( ),
		    destinationCollectionId = "http://desanti.org/collections/"+timestamp;

		if(collectionLabel != ""){
			D.request("newFile.txt", 
				{
					"collectionLabel": encodeURIComponent(collectionLabel),
					"destinationCollectionId": destinationCollectionId,
					"sourceCollectionId": line.id,
					"timestamp": timestamp,
					"user": D.userName()
				}, function(){
					updateFiles();
				}, true
			);
		}
	});

    	line.switchFiles.onclick = function(e){
		if(files.style.display === "block"){ 
			addToHeight(lines, 150);
			files.style.display = "none";
		}else{
			addToHeight(lines, -150);
			files.style.display = "block";
			updateFiles();
		}
            	e.stopPropagation( );
		return false;
	}

    }
})(DESANTI);
